<template>
  <div class="stuexam">
    <div class="toptitle">{{ examInfo.title }}</div>
    <div class="list">
      <!-- 每道题 -->
      <div
        class="li"
        :id="'id' + index"
        v-for="(item, index) in examInfo.questions"
        :key="item.id"
      >
        <div class="questiontype">
          <!-- 类型 -->
          <div class="type">
            <div class="num">{{ index + 1 }}</div>
            <div class="typetitle">{{ item.type }}</div>
          </div>
          <!-- 分值 -->
          <span class="score">分值：{{ item.scores }}</span>
        </div>
        <!-- 题目 -->
        <span
          class="title"
          v-html="item.type === '填空题' ? rep(item.title, index) : item.title"
        ></span>
        <!-- 选项 -->
        <div
          class="optionslist"
          v-show="item.type === '单选题' || item.type === '多选题'"
        >
          <!-- 选中 单选选项 -->
          <div
            v-show="item.type === '单选题'"
            :class="
              item.studentanswer === itemOpt.answerno
                ? 'optionsli wrong'
                : 'optionsli'
            "
            @click="select(itemOpt.answerno, index, item.type)"
            v-for="(itemOpt, indexOpt) in item.answers"
            :key="itemOpt.id"
          >
            <div class="left">
              <!-- 选项  单选题-->
              <div class="opt">{{ arr[indexOpt] }}</div>
              <!-- 答案 -->
              <span style="font-size: 13px">{{ itemOpt.content }}</span>
            </div>
          </div>
          <!-- 选项 多选题 -->
          <div
            v-show="item.type === '多选题'"
            :class="
              item.studentanswer == null
                ? 'optionsli'
                : item.studentanswer.indexOf(itemOpt.answerno) > -1
                ? 'optionsli wrong'
                : 'optionsli'
            "
            @click="select(itemOpt.answerno, index, item.type)"
            v-for="(itemOpt, indexOpt) in item.answers"
            :key="itemOpt.id"
          >
            <div class="left">
              <!-- 选项    多选 checked-->
              <div class="opt checked">{{ arr[indexOpt] }}</div>
              <!-- 答案 -->
              <span style="font-size: 13px">{{ itemOpt.content }}</span>
            </div>
          </div>
        </div>
        <!-- 判断题 -->
        <div class="optionslist" v-show="item.type === '判断题'">
          <!-- 正确 -->
          <div
            :class="
              item.studentanswer === '正确' ? 'optionsli wrong' : 'optionsli'
            "
            @click="judge('正确', index)"
          >
            <div class="left">
              <div class="opt">
                {{ item.studentanswer === '正确' ? '√' : '' }}
              </div>
              <span>正确</span>
            </div>
          </div>
          <!-- 错误 -->
          <div
            :class="
              item.studentanswer === '错误' ? 'optionsli wrong' : 'optionsli'
            "
            @click="judge('错误', index)"
          >
            <div class="left">
              <div class="opt">
                {{ item.studentanswer === '错误' ? '√' : '' }}
              </div>
              <span>错误</span>
            </div>
          </div>
        </div>
        <!-- 问答题 -->
        <el-input
          v-show="item.type === '问答题'"
          v-model="item.studentanswer"
          rows="5"
          type="textarea"
          placeholder="请输入问答"
        />
      </div>
    </div>
    <!-- 答题卡 -->
    <div class="answer">
      <div class="sheet">答题卡</div>
      <div class="nums">
        <div class="box"></div>
        <span>已答</span>
        <div class="boxwrong"></div>
        <span>未答</span>
      </div>
      <!-- 题目的序号 -->
      <div class="answerbox">
        <!-- 已达 wrong box   未答 box -->
        <div
          @click="location(index)"
          :class="item.studentanswer ? 'wrong box' : 'box'"
          v-for="(item, index) in examInfo.questions"
          :key="item.id"
        >
          {{ index + 1 }}
        </div>
      </div>
      <div class="bottom">
        <p>
          共<span>{{ examInfo.questions ? examInfo.questions.length : 0 }}</span
          >题，剩余<span>{{ examInfo.questions ? answered : 0 }}</span
          >题未完成
        </p>
        <el-popconfirm
          @confirm="submit"
          :title="
            (examInfo.questions
              ? answered > 0
                ? '你还有' + (examInfo.questions ? answered : 0) + '题未答'
                : '答题时间未结束'
              : 0) + '，确定要提交吗?'
          "
        >
          <template #reference>
            <el-button class="buttons" type="primary">交卷</el-button>
          </template>
        </el-popconfirm>
      </div>
    </div>
    <!-- 倒计时 -->
    <div class="timebox" v-show="examInfo.limittime > 0">
      <el-icon><AlarmClock /></el-icon>
      <span class="title">倒计时</span>
      <span class="time">{{ endTime }}</span>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, toRefs, watchEffect, nextTick,onUnmounted } from 'vue';
import { AlarmClock } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { getTestStart, postStudentanswerAdd } from '../../api/test';

const router = useRouter();
const route = useRoute();
console.log(route.query.testid);
const data: any = reactive({
  testid: 0,
  examInfo: { limittime: 0 },
  answered: 0,
  endTime: '',
  arr: [
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
  ],
});
const { arr, examInfo, answered, endTime } = toRefs(data);

// 试题打乱方法
const random = (arr: any) => {
  for (let i = 0; i < arr.length; i++) {
    var randomIndex = Math.floor(Math.random() * (i + 1));
    var itemAtIndex = arr[randomIndex];
    arr[randomIndex] = arr[i];
    arr[i] = itemAtIndex;
  }
  return arr;
};

// 获取考试题目（开始考试）
const testStart = async () => {
  const res: any = await getTestStart({ testid: route.query.testid });
  console.log(res);
  if (res.errCode === 10000) {
    data.examInfo = res.data;
    // 从缓存中取出历史答题
    let getitemExam = JSON.parse(
      sessionStorage.getItem("examInfo" + data.examInfo.id) as string
    );
    const studentid = sessionStorage.getItem('studentid');
    // 如果缓存有数据并且学生id和当前学生登录id相等
    if (getitemExam != null && getitemExam != ""&&studentid==getitemExam.studentId){
      // 如果是当前的这套试卷 从缓存中回显
      if (data.examInfo.id === getitemExam.id){
        data.examInfo = getitemExam;
        // 填空题回显数据
        nextTick(() => {
          document.querySelectorAll(".input").forEach((item: any) => {
            let _index = item.getAttribute("data-index");
            document
              .querySelectorAll(".input" + _index)
              .forEach((ite: any, index: number) => {
                ite.value =
                getitemExam.questions[_index].studentanswer.split("|")[index] ===
                  undefined
                    ? ""
                    : getitemExam.questions[_index].studentanswer.split("|")[index];
              });
          });
        });
      }else {
        data.examInfo = res.data;
      }
    }
    // 获取填空题答案
    nextTick(() => {
      document.querySelectorAll('.input').forEach((item: any) => {
        item.oninput = function () {
          let _index = this.getAttribute('data-index');
          let vals: any = [];
          document.querySelectorAll('.input' + _index).forEach((itm: any) => {
            if (itm.value) vals.push(itm.value);
          });
          data.examInfo.questions[_index].studentanswer =
            vals.length == 0 ? null : vals.join('|');
        };
      });
    });
     // 是否打乱试题
     if (data.examInfo.qorder === 1) {
      data.examInfo.questions = random(data.examInfo.questions);
    }
    // 是否打乱选项
    if (data.examInfo.aorder === 1) {
      data.examInfo.questions.forEach((item: any) => {
        if (item.type === "单选题" || item.type === "多选题") {
          item.answers = random(item.answers);
        }
      });
    }
    // 处理考试的倒计时
    if (examInfo.value.limittime > 0) {
      var timer = setInterval(() => {//实现定时调用的函数
        //获取当前时间
        var date = new Date();
        var now = Number(date);
        //设置截止时间
        var end =
          Number(new Date(data.examInfo.studentStartTime)) +
          examInfo.value.limittime * 60 * 1000;
        //获取截止时间和当前时间的时间差
        var leftTime = end - now;
        //定义变量 d,h,m,s分别保存天数，小时，分钟，秒
        var d: any, h, m, s;
        //判断剩余天数，时，分，秒
        if (leftTime > 0) {
          d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
          h = Math.floor((leftTime / 1000 / 60 / 60) % 24);
          m = Math.floor((leftTime / 1000 / 60) % 60);
          s = Math.floor((leftTime / 1000) % 60);
          if (String(h).length === 1) {
            h = "0" + h;
          }
          if (String(m).length === 1) {
            m = "0" + m;
          }
          if (String(s).length === 1) {
            s = "0" + s;
          }
          data.endTime = h + ":" + m + ":" + s;
        } else {
          data.endTime = "00:00:00";
          clearInterval(timer);//解除计时器的函数
          submit();// 到考试时间的时候自动交卷
        }
      }, 1000);
    }
  }
};
testStart();

// 单选多选
const select = (e: string, index: number, type: string) => {
  if (type === '单选题') {
    data.examInfo.questions[index].studentanswer = e;
  } else if (type === '多选题') {
    if (data.examInfo.questions[index].studentanswer == null) {
      data.examInfo.questions[index].studentanswer = '|' + e;
    } else {
      let arrIndex = data.examInfo.questions[index].studentanswer.indexOf(e);
      if (arrIndex > -1) {
        data.examInfo.questions[index].studentanswer = data.examInfo.questions[
          index
        ].studentanswer.replace('|' + e, '');
      } else {
        data.examInfo.questions[index].studentanswer =
          data.examInfo.questions[index].studentanswer + '|' + e;
      }
    }
  }
};

// 判断题判断对错
const judge = (e: string, index: number) => {
  data.examInfo.questions[index].studentanswer = e;
};

// 定位（瞄点）
const location = (index: number) => {
  let itemTop: any = document.getElementById('id' + index);
  window.scrollTo({ top: itemTop.offsetTop, behavior: 'smooth' });
};

watchEffect(() => {
  // 处理未答题的数量
  var num: number = 0;
  if (data.examInfo.id) {
    data.examInfo.questions.map((item: any) => {
      if (!item.studentanswer) {
        num = num + 1;
      }
    });
  }
  data.answered = num;
});

// 点击确定交卷
const submit = async () => {
  // 循环处理数据格式
  const dispose = data.examInfo.questions.map((item: any) => {
    let correctNum = 0;
    if (item.studentanswer && item.type === '多选题') {
      // 正确答案数组
      const answerArr = item.answer.split('|');
      // 学生答案
      const studentanswerArr = item.studentanswer
        .split('|')
        .filter((ite: any) => ite != '');
      console.log(answerArr, studentanswerArr);
      answerArr.forEach((item: any, index: number) => {
        studentanswerArr.forEach((item2: any, index2: number) => {
          if (item === item2 && answerArr.length === studentanswerArr.length) {
            correctNum += 1;
          }
        });
      });
    }
    const studentid = sessionStorage.getItem('studentid');
    return {
      testid: data.examInfo.id,
      studentid: studentid,
      questionid: item.id,
      answer: item.studentanswer === null ? '' : item.studentanswer,
      scores:
        item.type === '问答题' || item.type === '填空题'
          ? null
          : item.type === '单选题' || item.type === '判断题'
          ? item.studentanswer === item.answer
            ? item.scores
            : 0
          : !item.studentanswer
          ? 0
          : correctNum === item.answer.split('|').length
          ? item.scores
          : 0,
    };
})
  const res:any = await postStudentanswerAdd(dispose)
  console.log(res);
  if (res.errCode === 10000) {
    ElMessage.success('答题完毕！');
    router.push({ path: '/examresults', query: { id: data.examInfo.id } });
  } else {
    ElMessage.error(res.errMsg);
  }
};

// 替换方法(填空题)
const rep = (str: string, index: number) => {
  return str.replace(
    /\[\]/g,
    `<input data-index="${index}" onpaste="return false;" style="margin:0 2px" class="input input${index}" type="text" />`
  );
};

// 存储已经做过的考试题目
const examSetitem=()=>{
   const studentid = sessionStorage.getItem('studentid');
   sessionStorage.setItem(
     "examInfo" + data.examInfo.id,
     JSON.stringify({...data.examInfo,studentId:studentid})
   );
}
//浏览器属性事件(点击刷新的时候储存已经做过的考试题目)
window.onbeforeunload = function () {
  examSetitem()
};
// 卸载钩子(离开页面的时候进行销毁)
onUnmounted(() => {
  examSetitem()
});
</script>

<style lang="less" scoped>
.stuexam {
  padding: 0px 50px 0;
  display: flex;
  flex-direction: column;
  background-color: #fafbfd;
  .toptitle {
    font-size: 20px;
    margin-top: 20px;
  }
  // 试题开始
  .list {
    margin-top: 10px;
    .li {
      margin-top: 20px;
      display: flex;
      flex-direction: column;
      width: 1020px;
      padding-bottom: 20px;
      border-top: 1px #f0f0f0 solid;
      padding-top: 20px;
      .questiontype {
        display: flex;
        align-items: center;
        .type {
          height: 20px;
          width: 80px;
          border: 1px #3377f9 solid;
          display: flex;
          border-radius: 5px;
          overflow: hidden;
          font-size: 13px;
        }
        .num {
          width: 30%;
          height: 100%;
          background-color: #3377f9;
          color: #fff;
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .typetitle {
          flex: 1;
          height: 100%;
          background-color: #f1f5fb;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #3377f9;
        }
      }
      .score {
        font-size: 12px;
        color: #aca4ab;
        margin: 0 10px;
      }
    }
    .title {
      font-size: 15px;
      margin: 20px 0 20px;
    }
    .optionslist {
      .optionsli {
        height: 35px;
        width: 1000px;
        padding: 0 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border-radius: 3px;
        margin-bottom: 10px;
        border: 1px solid #fafbfd;
        .left {
          display: flex;
          align-items: center;
          .opt {
            width: 20px;
            height: 20px;
            border-radius: 50%;
            font-size: 12px;
            border: #d3d4d8 1px solid;
            color: #777f86;
            background-color: #fff;
            margin-right: 5px;
            display: flex;
            justify-content: center;
            align-items: center;
          }
          span {
            font-size: 14px;
          }
          .checked {
            border-radius: 5px;
          }
        }
      }
      .wrong {
        background-color: #f1f5fb;
        border: 1px solid #0089ff;

        .left {
          .opt {
            border: #0089ff 1px solid;
            color: #fff;
            background-color: #0089ff;
          }
        }
      }
    }
  }
  // 试题结束
  // 答题卡开始
  .answer {
    position: fixed;
    right: 0;
    top: 0;
    height: 100vh;
    width: 300px;
    background-color: #fff;
    .sheet {
      font-weight: bold;
      font-size: 20px;
      padding: 25px;
    }
    .nums {
      display: flex;
      padding: 0 25px 25px;
      align-items: center;
      .box {
        width: 16px;
        height: 16px;
        background-color: #f0f8ff;
        margin-right: 10px;
      }
      .boxwrong {
        width: 15px;
        height: 15px;
        border: 1px solid #e9e9e9;
        margin-right: 10px;
      }
      span {
        margin-right: 10px;
      }
    }
    .answerbox {
      display: flex;
      flex-wrap: wrap;
      padding: 0 20px;
      .box {
        width: 35px;
        height: 35px;
        border: 1px solid #e3e3e3;
        text-align: center;
        line-height: 35px;
        margin-left: 6px;
        margin-bottom: 6px;
        border-radius: 5px;
      }
      .wrong {
        background-color: #f0f8ff;
        color: #aab4fd;
      }
    }
    .bottom {
      padding: 0 20px;
      position: fixed;
      width: 260px;
      bottom: 20px;
      background-color: #fff;
      p {
        font-size: 12px;
        color: #989a99;
        span {
          color: #000;
        }
      }
      .buttons {
        width: 100%;
        font-size: 12px;
        margin-top: 10px;
      }
    }
  }
  .timebox {
    width: 85px;
    height: 100px;
    border-radius: 5px;
    background-color: #e98478;
    position: fixed;
    top: 20px;
    right: 320px;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #fff;
    .el-icon{
            font-size: 28px !important;
            margin-top: 15px;
        }
        .title{
            font-size: 12px;
            margin-top: 5px;
        }
        .time{
            font-size: 13px;
            margin-top: 8px;
        }
  }
}
</style>
